package cn.cnlee.tv.airport;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
import android.widget.TextView;

import cn.cnlee.tv.airport.service.HttpServer;
import cn.cnlee.tv.airport.service.ServerService;

public class MainActivity extends AppCompatActivity {

    public static final String TAG = MainActivity.class.getSimpleName();
    TextView tv;
    ImageView QrCode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Intent startIntent = new Intent(this, ServerService.class);
        startService(startIntent);

        tv = findViewById(R.id.ipAddress);
        String hostPort = "http://" + getLocalIpStr(this) + ":" + HttpServer.DEFAULT_SERVER_PORT;
        tv.setText(hostPort);

        QrCode = findViewById(R.id.qrCode);
        Bitmap mBitmap = ZXingUtils.createQRImage(hostPort + "/airport", 400, 400);
        QrCode.setImageBitmap(mBitmap);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Intent stopIntent = new Intent(this, ServerService.class);
        stopService(stopIntent);
    }

    //获取IP地址
    public static String getLocalIpStr(Context context) {
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        return intToIpAddr(wifiInfo.getIpAddress());
    }

    private static String intToIpAddr(int ip) {
        return (ip & 0xFF) + "."
                + ((ip >> 8) & 0xFF) + "."
                + ((ip >> 16) & 0xFF) + "."
                + ((ip >> 24) & 0xFF);
    }
}
